<?php
/**
 * Created by PhpStorm.
 * User: Jason
 * Date: 2017/7/25
 * Time: 11:08
 */

namespace Api\Service;


class ImageService
{
    /**
     * 通过谱单id获取谱单图片
     * @param $scoreId 谱单id
     * @return mixed
     */
    public function getImageUrlByScoreIds($scoreIds)
    {
        $map = array('score_id' => array('in', $scoreIds));
        $join = 'image b ON a.image_id=b.id AND a.is_cover=1';
        $Model = M('ImageScore a');
        $list = $Model->field('a.score_id, a.image_id, b.url')
            ->join($join)->where($map)
            ->select();

        $imagemap = array();
        foreach ($list as $key => $val) {
            $imagemap[$val['score_id']] = $val['url'];
        }

        return $imagemap;
    }

    /**
     * 通过曲谱id获取曲谱图片
     * @param $sheetId
     * @return mixed
     */
    public function getImageUrlBySheetId($sheetId)
    {
        $map = array(
            'sheet_id' => $sheetId,
            'is_delete' => 0
        );
        $model = M('ImageSheet a');
        $list = $model->field('a.sheet_id, a.image_id, b.url')
            ->join('image b ON a.image_id=b.id')->where($map)
            ->order('b.listorder, a.index, a.image_id')->select();
        foreach ($list as $key => $val) {
            $imagemap[$key] = $val['url'];
        }
        return $imagemap;
    }

    /**
     * 保存图片
     */
    public function save($param)
    {
        $Model = M('Image');
        $existImage = $Model->where(array("url"=>$param['url']))->find();
        if(!empty($existImage)) {
            $id = $existImage['id'];
        } else {
            $id = $Model->add($param);
        }
        return $id;
    }

    /**
     * 随机获取一张首图
     */
    public function randomScoreImg()
    {
        $map = array(
            'img_type' => 40,
        );
        $Model = M('Image');
        $idList = $Model->where($map)->field('id')->select();
        $ids = array_column($idList, 'id');
        $id = $ids[array_rand($ids)];
        return $id;

    }

}